package menu

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
	"strings"
	"wms/internal/svc"
	"wms/internal/types"
	"wms/model"
)

type ListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListLogic) List(req *types.MenuListRequest) (resp *types.MenuListResponse, err error) {
	resp = new(types.MenuListResponse)

	//1.查询所有路由
	var querys = make([]string, 0)
	var query string
	if len(req.Name) > 0 {
		querys = append(querys, fmt.Sprintf("title like '%%%s%%'", req.Name))
	}

	if len(querys) > 0 {
		query = " where " + strings.Join(querys, " and ")
	}

	//query += " order by parent_id desc, sort_id, id"
	query += " order by parent_id asc"

	//menus, err := l.svcCtx.MenuModel.FindByPage(l.ctx, fmt.Sprintf(" order by sort_id asc"))
	menus, err := l.svcCtx.MenuModel.FindByPage(l.ctx, query)
	switch err {
	case nil:
	case model.ErrNotFound:
		resp.Code = http.StatusOK
		resp.Msg = "成功"
		resp.Data = make([]types.Menu, 0)
		return resp, nil
	default:
		fmt.Printf("[Error]查询所有路由:%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	var list = make([]types.Menu, 0)
	for _, one := range menus {
		var meta types.Meta
		if err = json.Unmarshal([]byte(one.Meta), &meta); err != nil {
			fmt.Printf("[Error]路由[%s]meta解析失败:%s\n", one.Path, err.Error())
			resp.Code = http.StatusInternalServerError
			resp.Msg = "服务内部错误"
			return resp, nil
		}
		list = append(list, types.Menu{
			Id:         one.Id,
			Type:       one.Type,
			SortId:     one.SortId,
			ParentId:   one.ParentId,
			Path:       one.Path,
			Name:       one.Name,
			Component:  one.Component,
			Icon:       meta.Icon,
			Transition: meta.Transition,
			Hidden:     meta.Hidden,
			Fixed:      meta.Fixed,
			Perms:      meta.Perms,
		})
	}

	resp.Data = list
	resp.Code = http.StatusOK
	resp.Msg = "成功"

	return resp, nil
}
